import type { AxiosError, AxiosInstance, AxiosResponse } from 'axios'
import axios from 'axios'
import { Message } from '@arco-design/web-vue'

/* 服务器返回数据的的类型，根据接口文档确定 */
export interface Result<T = any> {
  code: number
  message: string
  data: T
}

const request: AxiosInstance = axios.create({
  baseURL: '/',
  timeout: 100 * 1000,
  withCredentials: true,
  headers: {
    common: {
      'X-Requested-With': 'XMLHttpRequest',
    },
    post: {
      'Content-Type': 'application/json;charset=utf-8',
    },
  },
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    try {
      if (parent.window) {
        // 业务系统需要设置tokenKey和tokenValue
        const authorizationKey = parent.window.localStorage.getItem('authorizationKey') as string
        const authorizationValue = parent.window.localStorage.getItem('authorizationValue')
        parent.window.localStorage.getItem('flowtoken')
        config.headers.flowtoken = parent.window.localStorage.getItem('flowtoken')
        config.headers[authorizationKey] = authorizationValue
      }
      else {
        console.error('只在在流程中心用iframe打开，才能获取token!')
      }
    }
    catch (e) {
      config.headers.flowtoken = localStorage.getItem('flowtoken')
      const authorizationKey = window.localStorage.getItem('authorizationKey') as string
      config.headers[authorizationKey] = window.localStorage.getItem('authorizationValue')
      console.error(`获取父窗口的token失败！${e}`)
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response && response.status === 200) {
      const code = response.data.code
      const msg = response.data.msg
      if (code === '100') {
        // 条件判断，自行和后端商量定义
        return Promise.resolve(response.data)
      }
      else if (code === 400) {
        // 自定义处理
        return Promise.reject(msg)
      }
      else if (code === '101') {
        Message.error(msg)
        return Promise.reject(msg)
      }
      else {
        // 错误处理
        return Promise.reject(response.data)
      }
    }
    else {
      return Promise.reject(response?.data)
    }
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  },
)

export default request
